import request from './request.js'
import { isBrowser } from '../utils/index.js'
const auth = "authorization"

function setItem(key, value) {
  if (isBrowser()) {
    localStorage.setItem(key, value)
  }
}

function getItem(key) {
  if (isBrowser()) {
    return localStorage.getItem(key)
  }
}

function removeItem(key) {
  if (isBrowser()) {
    localStorage.removeItem(key)
  }
}

export async function login(loginId, loginPwd) {
  const resp = await request.post('/api/user/login', {
    loginId,
    loginPwd
  })
  if (resp.data.code === 0) {
    const token = resp.headers[auth]
    setItem('token', token)
  } else {
    removeItem('token')
  }
  return resp.data
}

export async function whoAmi () {
  const token = getItem("token")
  if (!token) {
    return {
      code: 0,
      message: "",
      data: null
    }
  }
  const resp = request.get("/api/user/whoami", {
    headers: {
      [auth]: token
    }
  })
  return resp.data
}